﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 效率测量用户控件
    /// 功能：配置预设条件、工作条件，执行效率测量并保存结果
    /// </summary>
    public partial class UcEfficiencyMeasurement : UserControl
    {
        #region 字段定义

        private int channelCount = AppConfig.ChannelCount;
        private int inputHeight = 28;
        protected List<ChannelData> channelDataList;
        protected Dictionary<string, UITextBox[]> workConditionControls;
        // 添加控件引用字段
        private UITextBox txtMeasurementCount;
        private UITextBox txtMeasurementTime;
        private UITextBox[,] txtBackgroundValues; // [通道索引, 0=α, 1=β]

        private GlobalPresetData globalPreset;

        // 预设条件控件
        private UITextBox txtGeometryFactor;
        private Dictionary<string, UITextBox[]> presetControls;

        // α 和 β 选择框
        private UICheckBox chkAlphaEnabled;
        private UICheckBox chkBetaEnabled;

        protected virtual string MeasurementType { get; set; } = "WorkingSourceEfficiency";
        #endregion
        #region 测量结果显示
        // 测量类型显示名称映射
        protected static readonly Dictionary<string, string> MeasurementTypeDisplayNames = new Dictionary<string, string>
{
    {"Background", "本底测量"},
    {"WorkingSourceEfficiency", "工作源效率测量"},
    {"StandardSourceEfficiency", "标准源效率测量"},
    {"WaterSample", "水样品测量"},
    {"BioSample", "生物样品测量"},
    {"GasSample", "气体样品测量"},
    {"EnvSample", "环境样品测量"}
};
        // ================================
        // 3. 通用化的查看最新结果方法
        // ================================

        /// <summary>
        /// 查看最新结果按钮点击事件 - 通用版本
        /// 根据组件的测量类型显示对应的最新多轮测量结果
        /// </summary>
        private async void BtnViewLatestResult_Click(object sender, EventArgs e)
        {
            string originalText = "查看最新结果"; // 在方法开始处
            try
            {
                var clickedButton = sender as UIButton;
                string measurementType = clickedButton?.Tag?.ToString() ?? MeasurementType;
                string displayName = GetMeasurementTypeDisplayName(measurementType);

                // 显示加载提示
                originalText = clickedButton?.Text ?? "查看最新结果";
                if (clickedButton != null)
                {
                    clickedButton.Enabled = false;
                    clickedButton.Text = "加载中...";
                }

                // 查找该类型的最新测量数据
                var latestMeasurementData = await FindLatestMeasurementByType(measurementType);

                if (latestMeasurementData == null)
                {
                    UIMessageBox.ShowWarning($"暂无{displayName}结果！\n请先完成{displayName}后再查看结果。");
                    return;
                }

                // 打开MultiRoundResultForm显示结果
                var resultForm = new MultiRoundResultForm(latestMeasurementData);
                resultForm.ShowDialog(this);

                System.Diagnostics.Debug.WriteLine($"已显示{displayName}最新测量结果，测量时间：{latestMeasurementData.StartTime:yyyy-MM-dd HH:mm:ss}");
            }
            catch (Exception ex)
            {
                string displayName = GetMeasurementTypeDisplayName(MeasurementType);
                UIMessageBox.ShowError($"查看{displayName}最新结果失败：{ex.Message}");
                System.Diagnostics.Debug.WriteLine($"查看{displayName}最新结果失败: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                var clickedButton = sender as UIButton;
                if (clickedButton != null)
                {
                    clickedButton.Enabled = true;
                    clickedButton.Text = originalText;
                }
            }
        }

        /// <summary>
        /// 根据测量类型查找最新的测量数据 - 通用方法
        /// </summary>
        /// <param name="measurementType">测量类型（如"WaterSample", "BioSample"等）</param>
        /// <returns>最新的测量数据，如果不存在返回null</returns>
        private async Task<MultiRoundMeasurementData> FindLatestMeasurementByType(string measurementType)
        {
            MultiRoundMeasurementData latestData = null;
            DateTime latestTime = DateTime.MinValue;

            try
            {
                // 遍历所有通道查找指定类型的测量数据
                for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                {
                    try
                    {
                        var measurementData = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);

                        if (measurementData != null && measurementData.StartTime > latestTime)
                        {
                            latestTime = measurementData.StartTime;
                            latestData = measurementData;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"检查通道 {channelIndex + 1} {measurementType} 数据时出错: {ex.Message}");
                        // 继续检查其他通道
                    }
                }

                // 记录查找结果
                if (latestData != null)
                {
                    string displayName = GetMeasurementTypeDisplayName(measurementType);
                    System.Diagnostics.Debug.WriteLine($"找到最新{displayName}数据：");
                    System.Diagnostics.Debug.WriteLine($"  测量时间: {latestData.StartTime:yyyy-MM-dd HH:mm:ss} - {latestData.EndTime:yyyy-MM-dd HH:mm:ss}");
                    System.Diagnostics.Debug.WriteLine($"  总轮数: {latestData.TotalRounds}");
                    System.Diagnostics.Debug.WriteLine($"  参与通道: {latestData.ChannelResults.Count} 个");
                    System.Diagnostics.Debug.WriteLine($"  测量ID: {latestData.MeasurementId}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"未找到任何{measurementType}测量数据");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"查找最新{measurementType}测量数据失败: {ex.Message}");
                throw;
            }

            return latestData;
        }

        /// <summary>
        /// 获取测量类型的显示名称
        /// </summary>
        /// <param name="measurementType">英文测量类型</param>
        /// <returns>中文显示名称</returns>
        private string GetMeasurementTypeDisplayName(string measurementType)
        {
            return MeasurementTypeDisplayNames.ContainsKey(measurementType)
                ? MeasurementTypeDisplayNames[measurementType]
                : measurementType;
        }
        #endregion
        #region 构造函数和初始化

        public UcEfficiencyMeasurement()
        {
            InitializeComponent();
            InitializeControls();               // 初始化所有控件字典
            RefreshWorkConditionData();         // 加载数据
            globalPreset = GlobalPresetManager.LoadGlobalPreset(); // 加载全局预设
            LoadChannelData();
            // 构建界面
            BuildPreset();
            BuildSpacer(1);
            BuildWork();
            BuildSpacer(3);
            BuildDuration();
            BuildSpacer(5, 26);
            BuildButtons();
            LoadMeasurementSettings();
            LoadPresetData();                   // 加载预设数据到界面
        }

        /// <summary>
        /// 初始化所有控件字典
        /// </summary>
        private void InitializeControls()
        {
            InitializeWorkConditionControls();
            InitializePresetControls();
        }

        /// <summary>
        /// 初始化工作条件控件字典
        /// </summary>
        protected virtual void InitializeWorkConditionControls()
        {
            workConditionControls = new Dictionary<string, UITextBox[]>
            {
                ["alphaBackground"] = new UITextBox[channelCount],
                ["betaBackground"] = new UITextBox[channelCount],
                ["alphaWorkEfficiency"] = new UITextBox[channelCount],
                ["betaWorkEfficiency"] = new UITextBox[channelCount],
                ["alphaStandardEfficiency"] = new UITextBox[channelCount],
                ["betaStandardEfficiency"] = new UITextBox[channelCount]
            };
        }

        /// <summary>
        /// 初始化预设条件控件字典
        /// </summary>
        private void InitializePresetControls()
        {
            presetControls = new Dictionary<string, UITextBox[]>
            {
                ["alphaSurfaceEmission"] = new UITextBox[channelCount],   // α表面发射率
                ["betaSurfaceEmission"] = new UITextBox[channelCount]     // β表面发射率
            };
        }

        /// <summary>
        /// 加载通道数据
        /// </summary>
        protected virtual void LoadChannelData()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();

                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载通道数据失败：{ex.Message}");
                channelDataList = new List<ChannelData>();
                for (int i = 0; i < channelCount; i++)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = i });
                }
            }
        }

        /// <summary>
        /// 加载工作条件数据到界面控件
        /// </summary>
        protected virtual void LoadWorkConditionData()
        {
            try
            {
                for (int i = 0; i < channelCount; i++)
                {
                    var workCondition = channelDataList[i].WorkConditions;

                    if (workConditionControls["alphaBackground"][i] != null)
                        workConditionControls["alphaBackground"][i].Text = workCondition.AlphaBackground.ToString("0.######");

                    if (workConditionControls["betaBackground"][i] != null)
                        workConditionControls["betaBackground"][i].Text = workCondition.BetaBackground.ToString("0.######");

                    if (workConditionControls["alphaWorkEfficiency"][i] != null)
                        workConditionControls["alphaWorkEfficiency"][i].Text = workCondition.AlphaWorkEfficiency.ToString("0.##");

                    if (workConditionControls["betaWorkEfficiency"][i] != null)
                        workConditionControls["betaWorkEfficiency"][i].Text = workCondition.BetaWorkEfficiency.ToString("0.##");

                    if (workConditionControls["alphaStandardEfficiency"][i] != null)
                        workConditionControls["alphaStandardEfficiency"][i].Text = workCondition.AlphaStandardEfficiency.ToString("0.##");

                    if (workConditionControls["betaStandardEfficiency"][i] != null)
                        workConditionControls["betaStandardEfficiency"][i].Text = workCondition.BetaStandardEfficiency.ToString("0.##");
                }

                // 加载测量设置
                if (channelDataList.Count > 0)
                {
                    var workCondition = channelDataList[0].WorkConditions;
                    var txtCount = this.Controls.Find("txtMeasurementCount", true).FirstOrDefault() as UITextBox;
                    var txtTime = this.Controls.Find("txtMeasurementTime", true).FirstOrDefault() as UITextBox;

                    if (txtCount != null)
                        txtCount.Text = workCondition.MeasurementCycle.ToString();
                    if (txtTime != null)
                        txtTime.Text = workCondition.MeasurementTime.ToString("0.#");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载工作条件数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 保存工作条件数据到配置文件（实现双向绑定）
        /// 从界面控件读取数据并保存到配置文件
        /// 参考UcWaterSampleCheck.cs的SaveWorkConditionToConfig方法
        /// </summary>
        private bool SaveWorkConditionToConfig()
        {
            try
            {
                // 保存各通道的工作条件数据
                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];
                    var workCondition = channelData.WorkConditions;

                    // 从控件读取并保存各个工作条件数据
                    if (workConditionControls["alphaBackground"][i] != null &&
                        double.TryParse(workConditionControls["alphaBackground"][i].Text, out double alphaBackground))
                    {
                        workCondition.AlphaBackground = alphaBackground;
                    }

                    if (workConditionControls["betaBackground"][i] != null &&
                        double.TryParse(workConditionControls["betaBackground"][i].Text, out double betaBackground))
                    {
                        workCondition.BetaBackground = betaBackground;
                    }

                    if (workConditionControls["alphaWorkEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["alphaWorkEfficiency"][i].Text, out double alphaWorkEff))
                    {
                        workCondition.AlphaWorkEfficiency = alphaWorkEff;
                    }

                    if (workConditionControls["betaWorkEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["betaWorkEfficiency"][i].Text, out double betaWorkEff))
                    {
                        workCondition.BetaWorkEfficiency = betaWorkEff;
                    }

                    if (workConditionControls["alphaStandardEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["alphaStandardEfficiency"][i].Text, out double alphaStdEff))
                    {
                        workCondition.AlphaStandardEfficiency = alphaStdEff;
                    }

                    if (workConditionControls["betaStandardEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["betaStandardEfficiency"][i].Text, out double betaStdEff))
                    {
                        workCondition.BetaStandardEfficiency = betaStdEff;
                    }
                }

                // 保存测量设置（所有通道使用相同值）
                if (txtMeasurementCount != null &&
                    int.TryParse(txtMeasurementCount.Text, out int measurementCycle))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementCycle = measurementCycle;
                    }
                }

                if (txtMeasurementTime != null &&
                    double.TryParse(txtMeasurementTime.Text, out double measurementTime))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementTime = measurementTime;
                    }
                }

                // 保存到文件
                bool saved = ChannelDataManager.SaveAllChannelData(channelDataList);

                if (saved && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[效率测量] 工作条件已保存到配置文件");
                }

                return saved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[效率测量] 保存工作条件失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 加载预设数据到界面
        /// 从标准源测量结果中加载，如果没有则使用默认值
        /// </summary>
        // 修改 LoadPresetData 方法
        private void LoadPresetData()
        {
            try
            {
                // 加载全局几何因子
                if (txtGeometryFactor != null)
                    txtGeometryFactor.Text = globalPreset.GeometryFactor.ToString();

                // 加载各通道的表面发射率数据
                for (int i = 0; i < channelCount && i < channelDataList.Count; i++)
                {
                    var channelPreset = channelDataList[i].PresetConditions;

                    if (presetControls["alphaSurfaceEmission"][i] != null)
                        presetControls["alphaSurfaceEmission"][i].Text = channelPreset.AlphaSurfaceEmission.ToString();

                    if (presetControls["betaSurfaceEmission"][i] != null)
                        presetControls["betaSurfaceEmission"][i].Text = channelPreset.BetaSurfaceEmission.ToString();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载预设数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 刷新工作条件数据
        /// </summary>
        public virtual void RefreshWorkConditionData()
        {
            LoadChannelData();
            LoadWorkConditionData();
        }
        /// <summary>
        /// 加载测量设置到界面
        /// </summary>
        private void LoadMeasurementSettings()
        {
            try
            {
                if (channelDataList.Count > 0)
                {
                    var workCondition = channelDataList[0].WorkConditions;

                    // 使用保存的控件引用，避免查找
                    if (txtMeasurementCount != null)
                        txtMeasurementCount.Text = workCondition.MeasurementCycle.ToString();

                    if (txtMeasurementTime != null)
                        txtMeasurementTime.Text = workCondition.MeasurementTime.ToString("0.#");

                    // 加载各通道的本底数据
                    if (txtBackgroundValues != null)
                    {
                        for (int i = 0; i < channelCount && i < channelDataList.Count; i++)
                        {
                            var channelWorkCondition = channelDataList[i].WorkConditions;
                            if (txtBackgroundValues[i, 0] != null)
                                txtBackgroundValues[i, 0].Text = channelWorkCondition.AlphaBackground.ToString("0.######");
                            if (txtBackgroundValues[i, 1] != null)
                                txtBackgroundValues[i, 1].Text = channelWorkCondition.BetaBackground.ToString("0.######");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载测量设置失败: {ex.Message}");
            }
        }

        #endregion

        #region 界面构建方法

        /// <summary>
        /// 构建预设条件区域（几何因子 + 2π表面发射率）
        /// </summary>
        private void BuildPreset()
        {
            var group = new UIGroupBox
            {
                Text = "预设条件",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 12, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = channelCount + 1,
                RowCount = 5,
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));
            for (int i = 0; i < channelCount; i++)
                tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / channelCount));

            int row = 0;

            // Row0: 几何因子
            tbl.Controls.Add(new UILabel() { Text = "几何因子", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            txtGeometryFactor = new UITextBox() { Text = "0.9", Width = 60, Dock = DockStyle.Left, Margin = new Padding(6, 0, 0, 0) };
            tbl.Controls.Add(txtGeometryFactor, 1, row);
            row++;

            // Row1: 2π表面发射率标题
            var lblSurface = new UILabel()
            {
                Text = "2π表面发射率(表面粒子数/min)",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleRight
            };
            tbl.Controls.Add(lblSurface, 0, row);
            tbl.SetColumnSpan(lblSurface, 2);
            row++;

            // Row2: 通道表头
            tbl.Controls.Add(new UILabel() { Text = "", Dock = DockStyle.Fill }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                tbl.Controls.Add(new UILabel()
                {
                    Text = $"通道{i + 1}",
                    Dock = DockStyle.Left,
                    AutoSize = true,
                    Margin = new Padding(6, 0, 0, 0),
                    TextAlign = ContentAlignment.MiddleLeft
                }, i + 1, row);
            }
            row++;

            // Row3: α行（添加选择框）
            var alphaPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.LeftToRight,
                AutoSize = true,
                Margin = new Padding(0)
            };

            chkAlphaEnabled = new UICheckBox
            {
                Text = "",
                Checked = true,
                AutoSize = true,
                Margin = new Padding(0, 0, 5, 0)
            };
            // 绑定事件：选择框改变时启用/禁用输入框
            chkAlphaEnabled.CheckedChanged += (s, e) =>
            {
                for (int i = 0; i < channelCount; i++)
                {
                    if (presetControls["alphaSurfaceEmission"][i] != null)
                    {
                        presetControls["alphaSurfaceEmission"][i].Enabled = chkAlphaEnabled.Checked;
                    }
                }
            };

            var lblAlpha = new UILabel
            {
                Text = "α",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Margin = new Padding(0)
            };

            alphaPanel.Controls.Add(chkAlphaEnabled);
            alphaPanel.Controls.Add(lblAlpha);
            tbl.Controls.Add(alphaPanel, 0, row);

            for (int i = 0; i < channelCount; i++)
            {
                var textBox = new UITextBox { Text = "1440", Width = 70, Dock = DockStyle.Left, Margin = new Padding(6, 4, 0, 4) };
                presetControls["alphaSurfaceEmission"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }
            row++;

            // Row4: β行（添加选择框）
            var betaPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.LeftToRight,
                AutoSize = true,
                Margin = new Padding(0)
            };

            chkBetaEnabled = new UICheckBox
            {
                Text = "",
                Checked = true,
                AutoSize = true,
                Margin = new Padding(0, 0, 5, 0)
            };
            // 绑定事件：选择框改变时启用/禁用输入框
            chkBetaEnabled.CheckedChanged += (s, e) =>
            {
                for (int i = 0; i < channelCount; i++)
                {
                    if (presetControls["betaSurfaceEmission"][i] != null)
                    {
                        presetControls["betaSurfaceEmission"][i].Enabled = chkBetaEnabled.Checked;
                    }
                }
            };

            var lblBeta = new UILabel
            {
                Text = "β",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Margin = new Padding(0)
            };

            betaPanel.Controls.Add(chkBetaEnabled);
            betaPanel.Controls.Add(lblBeta);
            tbl.Controls.Add(betaPanel, 0, row);

            for (int i = 0; i < channelCount; i++)
            {
                var textBox = new UITextBox { Text = "1594", Width = 70, Dock = DockStyle.Left, Margin = new Padding(6, 4, 0, 4) };
                presetControls["betaSurfaceEmission"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }

            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 0);
        }

        /// <summary>
        /// 构建工作条件区域（本底CPS）
        /// </summary>
        private void BuildWork()
        {
            var group = new UIGroupBox
            {
                Text = "工作条件",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 0, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = channelCount + 1,
                RowCount = 4,
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));
            for (int i = 0; i < channelCount; i++)
                tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / channelCount));

            // 初始化本底值控件数组
            txtBackgroundValues = new UITextBox[channelCount, 2];

            int row = 0;

            // Row0: 本底/CPS 标题
            var lblCpsTitle = new UILabel
            {
                Text = "本底/CPS：",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleRight
            };
            tbl.Controls.Add(lblCpsTitle, 0, row);
            row++;

            // Row1: 通道表头
            tbl.Controls.Add(new UILabel() { Text = "", Dock = DockStyle.Fill }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                tbl.Controls.Add(new UILabel
                {
                    Text = $"通道{i + 1}",
                    Dock = DockStyle.Left,
                    AutoSize = true,
                    Margin = new Padding(6, 0, 0, 0),
                    TextAlign = ContentAlignment.MiddleLeft
                }, i + 1, row);
            }
            row++;

            // Row2: α行
            tbl.Controls.Add(new UILabel { Text = "α", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtBackgroundValues[i, 0] = new UITextBox
                {
                    Text = "0",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Height = inputHeight,
                    Enabled = true,  // 改为可用
                    ReadOnly = false,  // 改为可编辑
                    BackColor = Color.White  // 改为白色背景
                };
                tbl.Controls.Add(txtBackgroundValues[i, 0], i + 1, row);
            }
            row++;

            // Row3: β行
            tbl.Controls.Add(new UILabel { Text = "β", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                txtBackgroundValues[i, 1] = new UITextBox
                {
                    Text = "0",
                    Width = 70,
                    Dock = DockStyle.Left,
                    Height = inputHeight,
                    Enabled = true,  // 改为可用
                    ReadOnly = false,  // 改为可编辑
                    BackColor = Color.White  // 改为白色背景
                };
                tbl.Controls.Add(txtBackgroundValues[i, 1], i + 1, row);
            }

            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 2);
        }

        /// <summary>
        /// 构建测量时长区域
        /// </summary>
        private void BuildDuration()
        {
            var group = new UIGroupBox
            {
                Text = "测量时长",
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(12),
                Margin = new Padding(16, 8, 16, 0)
            };

            var table = new TableLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                ColumnCount = 4,
                RowCount = 1,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            table.ColumnStyles.Clear();
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));

            table.RowStyles.Clear();
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            var lblCount = new UILabel
            {
                Text = "测量次数",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用 - 修改为可编辑（参考UcWaterSampleCheck.cs）
            txtMeasurementCount = new UITextBox
            {
                Name = "txtMeasurementCount",
                Text = "1",
                Width = 80,
                Margin = new Padding(0, 2, 24, 2),
                Enabled = true,  // 改为可用
                ReadOnly = false,  // 改为可编辑
                BackColor = Color.White,  // 改为白色背景
                Anchor = AnchorStyles.Left
            };

            var lblTime = new UILabel
            {
                Text = "测量时间(min)",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };

            // 保存控件引用 - 修改为可编辑（参考UcWaterSampleCheck.cs）
            txtMeasurementTime = new UITextBox
            {
                Name = "txtMeasurementTime",
                Text = "5",
                Width = 80,
                Margin = new Padding(0, 2, 0, 2),
                Enabled = true,  // 改为可用
                ReadOnly = false,  // 改为可编辑
                BackColor = Color.White,  // 改为白色背景
                Anchor = AnchorStyles.Left
            };

            table.Controls.Add(lblCount, 0, 0);
            table.Controls.Add(txtMeasurementCount, 1, 0);
            table.Controls.Add(lblTime, 2, 0);
            table.Controls.Add(txtMeasurementTime, 3, 0);

            group.Controls.Add(table);
            this.outerLayout.Controls.Add(group, 0, 6);

            group.Height = group.PreferredSize.Height;
        }

        /// <summary>
        /// 构建按钮区域
        /// </summary>
        private void BuildButtons()
        {
            panelButtons.AutoSize = true;
            panelButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            panelButtons.Dock = DockStyle.Top;
            panelButtons.Padding = new Padding(0);
            panelButtons.Margin = new Padding(16, 8, 16, 0);

            panelButtons.Controls.Clear();

            var panel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            var btnStartMeasurement = new UIButton
            {
                Text = "开始测量",
                Width = 110,
                Height = 36,
                Margin = new Padding(60, 0, 0, 0)
            };
            btnStartMeasurement.Click += BtnStartMeasurement_Click;

            var btnCancel = new UIButton
            {
                Text = "取消",
                Width = 110,
                Height = 36,
                Margin = new Padding(32, 0, 0, 0)
            };
            btnCancel.Click += BtnCancel_Click;

            // 查看最新结果按钮
            var btnViewLatestResult = new UIButton
            {
                Text = "查看最新结果",
                Width = 130,
                Height = 36,
                Margin = new Padding(20, 0, 0, 0),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Tag = MeasurementType // 使用Tag存储测量类型
            };
            btnViewLatestResult.Click += BtnViewLatestResult_Click;
            panel.Controls.Add(btnViewLatestResult);

            panel.Controls.Add(btnStartMeasurement);
            panel.Controls.Add(btnCancel);

            panelButtons.Controls.Add(panel);
            this.outerLayout.Controls.Add(panelButtons, 0, 8);
        }

        /// <summary>
        /// 构建间隔区域
        /// </summary>
        private void BuildSpacer(int row, int height = 12)
        {
            var spacer = new Panel { Height = height, Dock = DockStyle.Top, BackColor = Color.Transparent };
            this.outerLayout.Controls.Add(spacer, 0, row);
        }

        #endregion

        #region 事件处理和数据保存

        public event Action<int, int> OnMeasurementStarted;

        /// <summary>
        /// 开始测量按钮点击事件
        /// 验证数据并保存配置，然后开始测量
        /// </summary>
        private void BtnStartMeasurement_Click(object sender, EventArgs e)
        {
            ValidateAndSaveData();
            try
            {
                // 验证至少选择了 α 或 β
                if (chkAlphaEnabled != null && chkBetaEnabled != null)
                {
                    if (!chkAlphaEnabled.Checked && !chkBetaEnabled.Checked)
                    {
                        UIMessageBox.ShowWarning("请至少选择一种测量类型（α 或 β）");
                        return;
                    }
                }

                // 使用保存的控件引用，而不是查找
                if (txtMeasurementCount == null || txtMeasurementTime == null)
                {
                    UIMessageBox.ShowError("界面控件未正确初始化。");
                    return;
                }

                if (!int.TryParse(txtMeasurementCount.Text, out int measurementCount) ||
                    !int.TryParse(txtMeasurementTime.Text, out int measurementTime))
                {
                    UIMessageBox.ShowError("请输入有效的数字。");
                    return;
                }

                // === 新增：保存工作条件到配置文件（实现双向绑定）===
                bool workConditionSaved = SaveWorkConditionToConfig();
                if (!workConditionSaved)
                {
                    var result = MessageBox.Show("工作条件保存失败，是否继续进行测量？",
                                               "保存提示",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                OnMeasurementStarted?.Invoke(measurementCount, measurementTime);

                // 构建测量类型信息
                string measurementTypes = "";
                if (chkAlphaEnabled != null && chkBetaEnabled != null)
                {
                    if (chkAlphaEnabled.Checked && chkBetaEnabled.Checked)
                    {
                        measurementTypes = "α 和 β";
                    }
                    else if (chkAlphaEnabled.Checked)
                    {
                        measurementTypes = "α";
                    }
                    else if (chkBetaEnabled.Checked)
                    {
                        measurementTypes = "β";
                    }
                }

                // 更新成功消息，包含测量类型和工作条件保存状态
                string successMessage = $"开始效率测量：次数 {measurementCount}, 时间 {measurementTime} 分钟";
                if (!string.IsNullOrEmpty(measurementTypes))
                {
                    successMessage += $"\n测量类型：{measurementTypes}";
                }
                if (workConditionSaved)
                {
                    successMessage += "\n工作条件已保存到配置文件";
                }
                UIMessageBox.ShowSuccess(successMessage);

                this.Parent?.Hide();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"启动测量时发生错误：{ex.Message}");
            }
        }
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Parent?.Hide();
        }

        /// <summary>
        /// 验证并保存界面数据到通道配置
        /// 保存到标准源测量结果中
        /// </summary>
        private bool ValidateAndSaveData()
        {
            try
            {
                // 验证几何因子
                string geometryFactorText = txtGeometryFactor.Text?.Trim();

                // 验证几何因子
                if (!double.TryParse(geometryFactorText, out double geometryFactor))
                {
                    UIMessageBox.ShowError("几何因子数据格式错误");
                    return false;
                }
                globalPreset.GeometryFactor = geometryFactor;
                GlobalPresetManager.SaveGlobalPreset(globalPreset);
                // 验证并保存各通道数据（根据选择框状态）
                bool alphaEnabled = chkAlphaEnabled?.Checked ?? true;
                bool betaEnabled = chkBetaEnabled?.Checked ?? true;

                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];

                    // 只验证和保存选中的类型
                    if (alphaEnabled)
                    {
                        if (!double.TryParse(presetControls["alphaSurfaceEmission"][i]?.Text, out double alphaEmission))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的α表面发射率数据格式错误");
                            presetControls["alphaSurfaceEmission"][i]?.Focus();
                            return false;
                        }
                        // 保存 α 表面发射率
                        channelData.PresetConditions.AlphaSurfaceEmission = alphaEmission;
                    }

                    if (betaEnabled)
                    {
                        if (!double.TryParse(presetControls["betaSurfaceEmission"][i]?.Text, out double betaEmission))
                        {
                            UIMessageBox.ShowError($"通道 {i + 1} 的β表面发射率数据格式错误");
                            presetControls["betaSurfaceEmission"][i]?.Focus();
                            return false;
                        }
                        // 保存 β 表面发射率
                        channelData.PresetConditions.BetaSurfaceEmission = betaEmission;
                    }

                    ChannelDataManager.SaveChannelData(i, channelData);
                }

                // 打印保存信息
                if (AppConfig.LogPrint == 1)
                {
                    string savedTypes = "";
                    if (alphaEnabled && betaEnabled)
                        savedTypes = "α 和 β";
                    else if (alphaEnabled)
                        savedTypes = "α";
                    else if (betaEnabled)
                        savedTypes = "β";

                    Console.WriteLine($"[效率测量] 已保存预设条件：{savedTypes}");
                }

                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存数据时发生错误：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 刷新通道数据和界面显示
        /// </summary>
        public void RefreshData()
        {
            try
            {
                LoadChannelData();
                LoadMeasurementSettings();

                // 强制刷新界面
                this.Invalidate();
                this.Update();

                System.Diagnostics.Debug.WriteLine("UcStandardSourceEfficiencyMeasurement 数据和界面已刷新");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"刷新数据失败：{ex.Message}");
            }
        }
        #endregion


        #region 计算
        /// <summary>
        /// 获取几何因子
        /// </summary>
        public double GetGeometryFactor()
        {
            try
            {
                if (globalPreset != null)
                {
                    return globalPreset.GeometryFactor;
                }

                // 如果全局预设为空，尝试重新加载
                globalPreset = GlobalPresetManager.LoadGlobalPreset();
                return globalPreset?.GeometryFactor ?? 0.9; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取几何因子失败: {ex.Message}");
                return 0.9; // 返回默认值
            }
        }

        /// <summary>
        /// 获取指定通道的α表面发射率
        /// </summary>
        public double GetAlphaSurfaceEmission(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.AlphaSurfaceEmission ?? 1440;
                }
                return 1440; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的α表面发射率失败: {ex.Message}");
                return 1440;
            }
        }

        /// <summary>
        /// 获取指定通道的β表面发射率
        /// </summary>
        public double GetBetaSurfaceEmission(int channelIndex)
        {
            try
            {
                if (channelDataList != null && channelIndex >= 0 && channelIndex < channelDataList.Count)
                {
                    return channelDataList[channelIndex].PresetConditions?.BetaSurfaceEmission ?? 1594;
                }
                return 1594; // 默认值
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取通道{channelIndex + 1}的β表面发射率失败: {ex.Message}");
                return 1594;
            }
        }

        /// <summary>
        /// 获取所有通道的α表面发射率数组
        /// </summary>
        public double[] GetAllAlphaSurfaceEmissions()
        {
            double[] emissions = new double[channelCount];
            for (int i = 0; i < channelCount; i++)
            {
                emissions[i] = GetAlphaSurfaceEmission(i);
            }
            return emissions;
        }

        /// <summary>
        /// 获取所有通道的β表面发射率数组
        /// </summary>
        public double[] GetAllBetaSurfaceEmissions()
        {
            double[] emissions = new double[channelCount];
            for (int i = 0; i < channelCount; i++)
            {
                emissions[i] = GetBetaSurfaceEmission(i);
            }
            return emissions;
        }

        /// <summary>
        /// 刷新数据并重新加载预设条件
        /// </summary>
        public void RefreshPresetData()
        {
            try
            {
                LoadChannelData();
                globalPreset = GlobalPresetManager.LoadGlobalPreset();
                LoadPresetData();
                System.Diagnostics.Debug.WriteLine("UcEfficiencyMeasurement 预设数据已刷新");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"刷新预设数据失败: {ex.Message}");
            }
        }
        #endregion
    }
}